package com.example.musicbox.config;

import com.example.musicbox.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.stream.Collectors;

/**
 * @author : zhy
 * @since : 2022/8/1
 */
@RestControllerAdvice
public class AdviceExceprionController {

    private static final Logger LOGGER= LoggerFactory.getLogger(AdviceExceprionController.class);


    /**
     * 校验器拦截校验失败的信息，然后统一返回错误检验内容
     * @param e
     * @return
     */
    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public Result MethodArgumentNotValidExceptionHandler(Exception e)
    {
        String message = "";
        if (e instanceof MethodArgumentNotValidException) {
            // BeanValidation exception
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            message = ex.getBindingResult().getAllErrors().stream()
                    .map(ObjectError::getDefaultMessage)
                    .collect(Collectors.joining("; "));
        } else if (e instanceof ConstraintViolationException) {
            // BeanValidation GET simple param
            ConstraintViolationException ex = (ConstraintViolationException) e;
            message = ex.getConstraintViolations().stream()
                    .map(ConstraintViolation::getMessage)
                    .collect(Collectors.joining("; "));
        } else if (e instanceof BindException) {
            // BeanValidation GET object param
            BindException ex = (BindException) e;
            message = ex.getAllErrors().stream()
                    .map(ObjectError::getDefaultMessage)
                    .collect(Collectors.joining("; "));
        }
        LOGGER.error("用户信息输入有误");
        return Result.error(message);
    }


    /**
     * 统一返回自定义异常错误信息内容
     * @param e
     * @return
     */
    @ExceptionHandler(value = MyException.class)
    public Result MyExceptionHandler(Exception e)
    {
        MyException ex = (MyException) e;
        String message = ex.getMessage();
        LOGGER.error("自定义异常统一连接错误信息");
        return Result.error(message);
    }
}
